package cn.htsyb.synergy.utils;

import java.io.*;
import java.util.Base64;

/**
 * 
 * @author lakeside hubin_yuan.410@hotmail.com
 * @version V1.0.0
 * @since 1.0
 * @date 2022/5/11
 */
public class SerializeUtil {
    /**
     * 二进制反序列化为对象
     *
     * @param bytes
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return ois.readObject();
        }
    }

    /**
     * 16进制文本反序列化为对象
     *
     * @param contentHex
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object deserializeHex(String contentHex) throws IOException, ClassNotFoundException {
        byte[] persistentValue = Base64.getDecoder().decode(contentHex);
        return deserialize(persistentValue);
    }

    /**
     * 序列化对象为二进制
     *
     * @param obj
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static byte[] serialize(Object obj) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            return bos.toByteArray();
        }
    }

    /**
     * 序列化对象为16进制文本
     *
     * @param obj
     * @return
     * @throws IOException
     */
    public static String serializeHex(Object obj) throws IOException {
        byte[] objectBytes = serialize(obj);
        return Base64.getEncoder().encodeToString(objectBytes);
    }

}
